﻿//
// *************************************************************************************
// WP-Framework
//
// Developed by 
// Lukas Kretschmar (lkretschmar.dev@bluewin.ch)
//
// Switzerland, Copyright (c) 2013 lkretschmar
// This content is released under the MIT License (http://opensource.org/licenses/MIT).
//     
// ******************************************************************************************************************************
//
//
			

using System;

namespace KretschIT.WP_Fx.EasyMoq.Calls.Functions
{
    internal class FunctionMock<T> : IFunctionMock<T>, IFunction<T, object>
    {
        private object value;

        #region Setup

        public virtual void Returns(object value)
        {
            this.value = value;
        }

        private Action<IEventsOf<T>> eventCall;

        public void Raise(Action<IEventsOf<T>> eventCall)
        {
            this.eventCall = eventCall;
        }

        private Exception exception;

        public virtual void Throws(Exception exception)
        {
            this.exception = exception ?? new NullReferenceException();
        }

        #endregion

        #region Execute

        private Func<object, object> convert;

        public void SetValueConverter(Func<object, object> convert)
        {
            this.convert = convert;
        }

        public virtual object Execute(T obj)
        {
            this.ThrowExceptionIfExists();
            if (this.RaiseEventIfExists(obj))
            {
                return new EmptyValue();
            }
            return GetResult();
        }

        private void ThrowExceptionIfExists()
        {
            if (this.exception != null)
            {
                throw this.exception;
            }
        }

        private bool RaiseEventIfExists(T obj)
        {
            if (this.eventCall != null && obj is IEventsOf<T>)
            {
                this.eventCall((IEventsOf<T>)obj);
                return true;
            }
            return false;
        }

        private object GetResult()
        {
            if (convert != null)
            {
                return convert(this.value);
            }
            return this.value;
        }

        #endregion
    }
}
